package com.wxp.alice.lanfilemaster.Server.Base;

import android.util.Log;
import android.util.Pair;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import fi.iki.elonen.NanoHTTPD;

class RoutePair<H extends BaseRequestHandler> extends Pair<String, H> {
    public RoutePair(String route, H handler) {
        super(route, handler);
    }
}

public class BaseHttpServer extends NanoHTTPD {
    private final String TAG = "BaseHttpServer";
    // 路由映射表
    private final ArrayList<RoutePair<?>> mRouteTable = new ArrayList<>();

    public BaseHttpServer(int port) {
        super(port);
    }

    public BaseHttpServer(String hostname, int port) {
        super(hostname, port);
    }

    public <H extends BaseRequestHandler> void addRoute(String uri, H handler) {
        mRouteTable.add(new RoutePair<H>(uri, handler));
    }

    @Override
    public Response serve(IHTTPSession session) {
        return dispatchRouteHandler(session);
    }

    private Response dispatchRouteHandler(IHTTPSession session) {
        // TODO: 路由匹配
        String uri = session.getUri();
        Method method = session.getMethod();
        for (RoutePair<?> pair : mRouteTable) {
            String routeUri = pair.first;
            BaseRequestHandler handler = pair.second;
            if (Objects.equals(uri, routeUri)) {
                // 找到匹配的 handler
                try {
                    handler.setSession(session);
                    handler.handleMethod(method);
                    byte[] data = handler.getResponseData();
                    return newFixedLengthResponse(handler.getStatus(), handler.getMimeType(),
                            new ByteArrayInputStream(data), data.length);
                } catch (Exception e) {
                    Log.e(TAG, "Exception" + e);
                }
                break;
            }
        }
//        return newFixedLengthResponse(NanoHTTPD.Response.Status)
    }
}
